/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.projektjava;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Michal Polkorab
 */
public class EmployeeDAOImpl implements EmployeeDAO{

    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProjektPU");

  
    @Override
    public void create(Employee employee) {
        if (employee != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            em.persist(employee);
            em.getTransaction().commit();
            em.close();
        }      
    }

    @Override
    public Employee get(Long id) {
        EntityManager em = emf.createEntityManager();
        Employee employee = em.find(Employee.class, id);
        em.close();
        return employee;
    }

    @Override
    public boolean update(Employee employee) {
        if (employee != null){
            Employee employeefound = get(employee.getId());
            if (employeefound == null){return false;}
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            employeefound = employee;
            em.persist(employeefound);
            em.getTransaction().commit();
            em.close();
            return true;
        }
        return false;
    }

    @Override
    public void remove(Employee employee) {
        if (employee != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            Employee employeefound = em.find(Employee.class, employee.getId());
            if (employeefound != null){
                em.remove(employeefound);
            }
            em.getTransaction().commit();
            em.close();
        }  
    }

    public List<Employee> findByName(String surname) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT * FROM employee WHERE surname=" + surname); 
        List<Employee> employees = q.getResultList();
        em.getTransaction().commit();
        em.close();
        return employees;  
               
    }
    
}
